package com.dreamchaser.familydevice.controller;

import com.dreamchaser.familydevice.annotation.IgnoreUrl;
import com.dreamchaser.familydevice.constant.ResponseCode;
import com.dreamchaser.familydevice.domain.MessageVO;
import com.dreamchaser.familydevice.domain.dto.AccountDTO;
import com.dreamchaser.familydevice.domain.vo.input.UserVO;
import com.dreamchaser.familydevice.exception.BusinessException;
import com.dreamchaser.familydevice.po.User;
import com.dreamchaser.familydevice.service.ILoginService;
import com.dreamchaser.familydevice.util.Encode.MD5Util;
import com.dreamchaser.familydevice.util.system.JsonWebTokenUtil;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 注册、登陆
 */
@RestController
@Api(value = "注册登陆", tags = "注册登录")
@RequestMapping("login")
@Slf4j
public class Logincontroller {
    @Autowired
    ILoginService loginService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     * 过期时间3天免登录
     */
    private long dueDate = 24 * 3600 * 3;

    @IgnoreUrl
    @ApiOperation("登陆接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "userName", value = "账号", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)})
    @PostMapping("/login")
    public MessageVO login(@NotBlank(message = "用户名不可为空") @RequestParam String userName, @NotBlank(message = "密码不可为空") @RequestParam String password, HttpServletRequest request, HttpServletResponse response) {
        log.info("login--------strat");

        password = MD5Util.charToMd5(password);
        User user = loginService.login(userName, password);
        if (user != null) {
            AccountDTO accountDTO = new AccountDTO();

            accountDTO.setAccountId(user.getId())
                    .setAccount(user.getAccount())
                    .setEmail(user.getEmail())
                    .setName(user.getName())
                    .setWeChartId(user.getWeChartId())
                    .setMd5(user.getPassword())
                    .setKey(MD5Util.charToMd5(user.getAccount() + user.getPassword() + user.getAccount()));

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            log.debug(uuid);

            // 生成token
            String token = JsonWebTokenUtil.issueJWT(uuid, dueDate, accountDTO, SignatureAlgorithm.HS512);
            try {
                stringRedisTemplate.opsForValue().set(uuid, token, dueDate, TimeUnit.SECONDS);
            } catch (Exception e) {
                log.error("redis set error", e);
                return new MessageVO().back(ResponseCode.EXCEPTION, "系统异常");
            }
            log.debug(token);
            log.info("login--------end");
            HashMap<String, String> data = new HashMap<>();
            data.put("token", token);
            data.put("realName", accountDTO.getName());
            return new MessageVO().back(ResponseCode.OK, "登陆成功").setData(data);
        } else {
            return new MessageVO().back(ResponseCode.BUSINESS_EXCEPTION, "用户名或密码错误");
        }
    }

    /**
     * 注册
     *
     * @param userVO
     * @return
     */
    @ApiOperation("注册接口")
    @PostMapping("/register")
    @IgnoreUrl
    @Transactional(rollbackFor = Exception.class)
    public MessageVO register(@RequestBody UserVO userVO) {
        log.info("register--------start");
        String regex = "^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\\.[a-z]{2,}$";
        if (!StringUtils.isEmpty(userVO.getAccount())) {
            String account = loginService.selectAccount(userVO.getAccount());
            if (StringUtils.isEmpty(account)) {
                User user2 = new User();
                user2.setAccount(StringUtils.isEmpty(userVO.getAccount()) ? "" : userVO.getAccount());
                if (Pattern.matches(regex, StringUtils.isEmpty(userVO.getEmail()) ? "" : userVO.getEmail())) {
                    user2.setEmail(userVO.getEmail());
                } else {
                    throw new BusinessException("邮箱不合法");
                }

                user2.setName(StringUtils.isEmpty(userVO.getName()) ? "" : userVO.getName());
                user2.setPassword(MD5Util.charToMd5(StringUtils.isEmpty(userVO.getPassword()) ? "" : userVO.getPassword()));
                loginService.register(user2);


                return new MessageVO().back(ResponseCode.OK, "注册成功").setData(user2.getAccount());
            } else {
                return new MessageVO().back(ResponseCode.BUSINESS_EXCEPTION, "用户名重复");
            }
        } else {
            return new MessageVO().back(ResponseCode.BUSINESS_EXCEPTION, "账户名为空");
        }


    }

}
